iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0

單元測試

在昨天使用 mix new hello_world 產生的專案裡
有產生在 lib 資料夾內的 lib/hello_world.ex
與 test 資料夾內的 test/hello_world_test.exs

ex檔 vs exs檔

普通的 ex 檔案如這次的 hello_world.ex 會在執行前先編譯到 bytecode,
exs 是在要執行的時候才直譯,適合寫在測試、設定檔等只跑一次的工作

hello_world.ex

defmodule HelloWorld do
  def hello do
    :world
  end
end

hello_world_test.exs

defmodule HelloWorldTest do
  use ExUnit.Case

  test "greets the world" do
    assert HelloWorld.hello() == :world
  end
end

可以看到通常慣例上都會取同個名字加上 test (不強制但是比較好找)
檔名 hello_world.ex 對應 hello_world_test.exs
模組名稱 HelloWorld 對應 HelloWorldTest

首先在模組使用 use 來載入 ExUnit.Case
他會提供 test 語法 (其實是巨集)

在裡面呼叫函式並使用 assert 確認結果
可以直接比較執行結果與預期結果

result = HelloWorld.hello()
assert result == :world

也可以使用 pattern matching 來看該結果是不是 match

user = find_admin_user()
assert %{admin: true} = user

執行

執行專案所有的測試

mix test

只執行某個測試

mix test test/hello_world_test.exs

只執行某個測試檔案行數對應的測試

test/hello_world_test.exs:5

上一篇
mix 工具
系列文
通勤看手機就可讀懂的 Elixir 語言入門教學10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言